$(() => {
    let slides = []
    //渲染轮播图列表函数
    function renderSlidesList() {
        $('#slidesListBox').html(template('slidesListTPL', { slides }))
    }
    //轮播列表展示
    $.ajax({
        type: 'get',
        url: '/slides',
        success(res) {
            slides = res
            renderSlidesList()
        },
        error() {
            alert('获取轮播数据失败!')
        }
    })


    //图片上传
    $('#avatar').change(function () {
        const formData = new FormData()
        formData.append('avatar', this.files[0])
        $.ajax({
            type: 'post',
            url: '/upload',
            processData: false,
            contentType: false,
            data: formData,
            success(res) {
                $('#preview').attr('src', res[0].avatar)
                $('#hiddenInput').val(res[0].avatar)
            },
            error() {
                alert('图片上传失败!')
            }
        })

    })

    //添加轮播图表单提交
    $('#slidesADDForm').on('submit', function () {
        const formData = $(this).serialize()
        $.ajax({
            type: 'post',
            url: '/slides',
            data: formData,
            success(res) {
                slides.push(res)
                renderSlidesList()
                $('#preview').attr('src', '')
                $('#slidesADDForm')[0].reset()
            },
            error() {
                alert('添加失败')
            }
        })
        return false
    })

    //删除轮播图
    $('#slidesListBox').on('click', '#delBtn', function (e) {
        const id = e.target.dataset.id
        const result = confirm('您确定要删除吗?')
        if (!result) { return false }
        $.ajax({
            type: 'delete',
            url: `/slides/${id}`,
            success(res) {
                const index = slides.findIndex((v) => {
                    return v._id == res._id
                })
                slides.splice(index, 1)
                renderSlidesList()
            },
            error() {
                alert('删除失败!')
            }
        })
    })
})